package com.atguigu.wc;

import org.apache.flink.api.common.functions.FlatMapFunction;
import org.apache.flink.api.java.functions.KeySelector;
import org.apache.flink.api.java.tuple.Tuple2;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.datastream.KeyedStream;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.util.Collector;

public class WordCountStreamDemo {
    public static void main(String[] args) throws Exception {
        //todo 1 创建执行环境
        StreamExecutionEnvironment streamEnv = StreamExecutionEnvironment.getExecutionEnvironment();
        // todo 2 读取数据
        DataStreamSource<String> lineDS = streamEnv.readTextFile("input/word.txt");

        //todo 3.切分、转换数据、分组、聚合
        //  切分 转换
        SingleOutputStreamOperator<Tuple2<String, Integer>> words = lineDS.flatMap(new FlatMapFunction<String, Tuple2<String, Integer>>() {
            @Override
            public void flatMap(String s, Collector<Tuple2<String, Integer>> collector) throws Exception {
                String[] word = s.split(" ");
                for (String word1 : word) {
                    //转换成二元组 (word,1)
                    Tuple2<String, Integer> wordAndOne = Tuple2.of(word1, 1);
                    //通过采集器 向下游发送数据
                    collector.collect(wordAndOne);
                }
            }
        });
        //  todo 3.2分区聚合
        KeyedStream<Tuple2<String, Integer>, String> wordAndOneKey = words.keyBy(
                new KeySelector<Tuple2<String, Integer>, String>() {
                    @Override
                    public String getKey(Tuple2<String, Integer> value) throws Exception {
                        return value.f0;
                    }
                }
        );
        //todo 3.3 聚合
        SingleOutputStreamOperator<Tuple2<String, Integer>> sumDS = wordAndOneKey.sum(1);

        //todo 4 输出数据
        sumDS.print();

        //启动程序
        streamEnv.execute();
    }
}

